<template>
  <a-form :form="form" class="login-form" @submit.prevent="handleSubmit">
    <a-spin :spinning="spinning" :tip="tip" :size="'large'">
      <a-form-item>
        <a-auto-complete
          v-decorator="[
            'email',
            {
              rules: [{
                required: true, message: $t('pro.loginReg.loginMessage')
              }, {
                type: 'email', message: $t('pro.loginReg.loginWra')
              }]
            }
          ]"
          :placeholder="$t('pro.loginReg.loginPla')"
          @search="handleSearch"
        >
          <template slot="dataSource">
            <a-select-option v-for="email in result" :key="email">{{email}}</a-select-option>
          </template>
        </a-auto-complete>
      </a-form-item>

      <!-- 单击忘记密码展示 -->
      <div v-if="isResetPswForm" class="reset-btn-group flex-between">
        <a-form-item>
          <a-button
            type="primary"
            html-type="button"
            @click="toggleForm"
            v-text="$t('pro.loginReg.Back')"
          ></a-button>
        </a-form-item>
        <a-form-item>
          <a-button
            type="primary"
            :disabled="resetDisabled"
            @click="sendMail"
          >{{ sendMailButName }} {{ ssm }}</a-button>
        </a-form-item>
      </div>

      <!-- 找回密码模块 -->
      <div v-else>
        <a-form-item>
          <a-input
            v-decorator="[
            'passwordDigest',
            {
              rules: [{
                required: true, message: $t('pro.loginReg.passwordMess')
              }, {
                validator: validateToNextPassword
              }] }
          ]"
            :type="showPassword ? 'text' : 'password'"
            :placeholder="$t('pro.loginReg.passwordPla')"
          >
            <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
            <a-icon
              slot="addonAfter"
              style="cursor: pointer;"
              :type="showPassword ? 'eye-invisible' : 'eye'"
              @click="switchEye"
              v-if="showPswEye"
            />
          </a-input>
        </a-form-item>

        <!-- 记住密码 -->
        <!-- <a-form-item>
          <a-checkbox
            v-decorator="[
            'remember',
            {
              valuePropName: 'checked',
              initialValue: true,
            }
          ]"
          >{{$t('pro.loginReg.Remember')}}</a-checkbox>
        </a-form-item>-->

        <a-form-item>
          <a-button
            type="primary"
            html-type="submit"
            block
            class="login-form-button"
            v-text="$t('pro.loginReg.Login')"
          ></a-button>
        </a-form-item>
      </div>

      <div class="form-footer" v-if="!isResetPswForm">
        <a @click="toggleForm" v-text="$t('pro.loginReg.ForgotPas')"></a>
      </div>
    </a-spin>
  </a-form>
</template>

<script>
import { mapActions } from "vuex";
import { sendEmai } from "../../api/login";
import { vPassword } from "../../utils/validate";
import { handleSearch } from "../../utils/tool";

export default {
  name: "login",
  data: function() {
    return {
      isResetPswForm: false,
      showPassword: false,
      showPswEye: false,
      spinning: false, //加载
      form: this.$form.createForm(this),
      resetDisabled: false, //发送邮件之后禁用,
      sendMailButName: "",
      ssm: "",
      tip: this.$t("pro.loginReg.logining"),
      result: [],
      redirect: "/dashboard",
      aa: window.localStorage.locale
    };
  },
  props: {
    isupdatePwd: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query.lastPath || "/dashboard";
      },
      immediate: true
    },
    isupdatePwd(flay) {
      this.isResetPswForm = flay;
    }
  },

  methods: {
    ...mapActions(["Login"]),
    handleSearch(value) {
      //支持邮箱有那些
      handleSearch(value, this, "result");
    },
    handleSubmit() {
      this.form.validateFields((err, values) => {
        if (err == null) {
          this.spinning = true;
          const { Login } = this;
          Login(JSON.stringify(values))
            .then(res => {
              let { code, data } = res;
              if (code == 200) {
                window.localStorage.NEWLOGIN = data.isFirstLogin;
                setTimeout(() => {
                  this.tip = this.$t("pro.loginReg.loginSuccess");
                  window.sessionStorage.setItem("Authorization", data.token);
                  setTimeout(() => {
                    this.spinning = false;
                    this.$router.push(this.redirect);
                  }, 860);
                }, 860);
              } else {
                this.spinning = false;
              }
            })
            .catch(() => {
              this.spinning = false;
            });
        }
      });
    },
    // 切换登录 和 重置密码
    toggleForm() {
      this.isResetPswForm = !this.isResetPswForm;
      this.$emit("updatePwd", this.isResetPswForm);
    },

    //忘记密码后 输入邮箱点击发送 让用户在邮箱上跳转到修改密码
    sendMail() {
      this.$message.loading(this.$t("pro.public.action"), 2).then(() => {
        let email = this.form.getFieldValue("email");
        sendEmai(email)
          .then(res => {
            let { code } = res.data;
            if (code == 200) {
              this.sendMailButName = this.$t("pro.loginReg.HasBeenSent"); //已发送
              this.resetDisabled = true;
              let i = 60;
              const self = this;
              let inter = setInterval(() => {
                this.ssm = i;
                i--;
                if (i == -1) {
                  clearInterval(inter);
                  this.sendMailButName = self.$t("pro.settings.fromEmail"); //确定发送
                  this.ssm = "";
                  this.resetDisabled = false;
                }
              }, 1000);
            }
          })
          .catch(() => {
            this.resetDisabled = false;
          });
      });
    },

    validateToNextPassword(rule, value, callback) {
      if (value) {
        if (vPassword(value)) {
          callback();
        } else {
          callback(this.$t("pro.loginReg.passwordWra"));
        }
      } else {
        // 账号或密码为空执行回调, 参数为空字符串
        // 以显示对应模板中input required msg
        callback("");
      }
    },

    switchEye() {
      this.showPassword = !this.showPassword;
    }
  },
  created() {
    this.sendMailButName = this.$t("pro.settings.fromEmail");
  },
  destroyed() {
    //离开后修改登录 隐藏修改密码
    this.isResetPswForm = false;
    this.$emit("updatePwd", this.isResetPswForm);
  }
};
</script>

<style scoped>
.form-footer {
  margin-top: 10px;
}
#app.dark .ant-checkbox-wrapper,
.anticon {
  color: rgba(0, 0, 0, 0.65) !important;
}
</style>
